package com.life.wd.controller;

import com.life.wd.dto.ProductAddRequest;
import com.life.wd.dto.ProductQueryRequest;
import com.life.wd.dto.ProductUpdateRequest;
import com.life.wd.result.PageResult;
import com.life.wd.result.Result;
import com.life.wd.service.ProductService;
import com.life.wd.vo.ProductVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.IOException;

@RestController
@RequestMapping("/api/product")
@Slf4j
@Api(tags = "产品管理")
public class ProductController {

    // 全局异常处理
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e) {
        log.error("系统异常: ", e);
        return Result.error("系统异常: " + e.getMessage());
    }
    @Autowired
    private ProductService productService;

    /**
     * 添加产品
     */
    @PostMapping("/add")
    @ApiOperation("添加产品")
    public Result<Long> addProduct(@ModelAttribute ProductAddRequest request) {
        log.info("添加产品: {}", request);
        try {
            Long productId = productService.addProduct(request);
            return Result.success(productId);
        } catch (Exception e) {
            return Result.error("添加产品失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询产品列表
     */
    @ApiOperation("分页查询产品列表")
    @GetMapping("/list")
    public Result listProducts(
            @Validated ProductQueryRequest queryRequest) {
        PageResult result = productService.listProducts(queryRequest);
        return Result.success(result);
    }

    /**
     * 根据ID获取产品详情
     */
    @ApiOperation("根据ID获取产品详情")
    @GetMapping("/{id}")
    public Result<ProductVO> getProductById(
            @PathVariable @NotNull(message = "产品ID不能为空") Long id) {
        ProductVO product = productService.getProductById(id);
        return Result.success(product);
    }


    /**
     * 更新产品
     */
    @PostMapping("/update")
    @ApiOperation("更新产品")
    public Result<Boolean> updateProduct(@ModelAttribute ProductUpdateRequest request) {
        log.info("更新产品: {}", request);
        try {
            boolean success = productService.updateProduct(request);
            return Result.success(success);
        } catch (Exception e) {
            return Result.error("更新产品失败: " + e.getMessage());
        }
    }

    /**
     * 删除产品
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除产品")
    public Result<Boolean> deleteProduct(@PathVariable Long id) {
        try {
            boolean success = productService.deleteProduct(id);
            return Result.success(success);
        } catch (Exception e) {
            return Result.error("删除产品失败: " + e.getMessage());
        }
    }
}
